#coding: utf-8
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from taxonomy.forms import *


def addCategory( request, template_name ):
    if request.method == 'POST':
        form = AddCategoryForm( request.POST )
        if form.is_valid():
            category = form.save()
            return HttpResponseRedirect('')
    else:
        form = AddCategoryForm()
    return render_to_response( template_name, { 'form': form } )

#显示指定分类及其一级子分类。默认从所有顶级分类开始
def showCategories( request, template_name ):
    if request.method == 'GET':
        queryname = request.GET.get( 'name', None )
    elif request.method == 'POST':
        queryname = request.POST.get( 'name', None )
    else:
        queryname = None
    entrylist = []
    if queryname ==None:
        clist = Category.objects.filter( parent__isnull = True )
    else:
        clist = Category.objects.filter( name = queryname )    
    for category in clist:
        entrylist.append( category.category_and_sub() )
    return render_to_response( template_name, { 'entrylist': entrylist } )

#暂时不用的方法，作用是递归的显示以某个分类为根的分类树
def showCategoryTree( request, template_name ):
    if request.method == 'GET':
        queryname = request.GET.get( 'name', None )
        if queryname !=None:
            try:
                category = Category.objects.get( name = queryname )
            except Category.DoesNotExist:
                tree = {}
            else:
                tree = category.categoryTree()
        else:
            tree= {}
    else:
        tree = {}
    return render_to_response( template_name, { 'tree': tree } )

def addTag( request, template_name ):
    if request.method == 'POST':
        form = AddTagForm( request.POST )
        if form.is_valid():
            tag = form.save()
            return HttpResponseRedirect('')
    else:
        form = AddTagForm()
    return render_to_response( template_name, { 'form': form } )